﻿public class Solution {
    public int LargestSumAfterKNegations(int[] nums, int k) 
    {
        // 按绝对值排序
        Array.Sort(nums, Compare);

        for (int i = nums.Length - 1; i >= 0; i--)
        {
            if (k <= 0) break;

            if (nums[i] < 0)
            {
                k--;
                nums[i] = -nums[i];
            }
        }

        while (k > 0)
        {
            nums[0] = -nums[0];
            k--;
        }

        return nums.Sum();
    }

    private int Compare(int n1, int n2)
    {
        return Math.Abs(n1).CompareTo(Math.Abs(n2));
    }

    public static void Main(string[] args)
    {
        int[] nums = [2, -3, -1, 5, -4];
        int k = 2;

        Solution solution = new Solution();
        int res = solution.LargestSumAfterKNegations(nums, k);
        Console.WriteLine(res);
    }
}